package com.conf4j.kit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 类加载器工具类
 * 
 * @author dingnate
 */
public class ClassLoaderKit {
	ClassLoaderKit() {
	}

	/**
	 * 先获类加载器<br><br>
	 * 类加载器获取顺序：线程上下文类加器>clazz的类加载器
	 * @param clazz
	 * @return ClassLoader
	 */
	public static ClassLoader getClassLoader() {
		ClassLoader ret = Thread.currentThread().getContextClassLoader();
		return ret != null ? ret : ClassLoaderKit.class.getClassLoader();
	}

	/**
	 * 获取资源流<br><br>
	 * -D参数或"conf4j.properties"中conf4j.config.scaner.localPath=config/local/path，
	 * config/local/path中的配置文件覆盖类路径中对应的配置文件
	 * @param name 
	 * @return 资源流或者null
	 */
	public static InputStream getResourceAsStream(String name) {
		String configLocalPath = ConfKit.getConfigLocalPath();
		if (StrKit.isNotBlank(configLocalPath) && new File(configLocalPath, name).exists())
			try {
				return new FileInputStream(new File(configLocalPath, name));
			} catch (FileNotFoundException e) {
				// do nothing
			}
		return getClassLoader().getResourceAsStream(name);
	}
}
